package com.baozun.houji.order.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.baozhun.mall.common.arouter.RoutePath
import com.baozhun.mall.common.base.BaseActivity
import com.baozhun.mall.common.ext.showToast
import com.baozhun.mall.common.model.bean.ExpressInfoBean
import com.baozhun.mall.common.model.enums.RefundStatus
import com.baozhun.mall.common.util.Constants
import com.baozhun.mall.common.widget.dialog.CommonChooseDialog
import com.baozun.houji.order.R
import com.baozun.houji.order.databinding.ActivityRefundDetailBinding
import com.baozun.houji.order.model.bean.RefundDetailBean
import com.baozun.houji.order.util.order.OrderActionFinishListener
import com.baozun.houji.order.util.order.OrderActionManager
import com.baozun.houji.order.util.order.enums.OrderActionType
import com.baozun.houji.order.util.order.enums.OrderSource
import com.baozun.houji.order.viewmodel.RefundDetailViewModel
import com.blankj.utilcode.util.IntentUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.jaeger.library.StatusBarUtil
import me.hgj.jetpackmvvm.ext.util.copyToClipboard


/**
 * @Title：退款详情页面
 * @Description：
 * @Author：xing.luo
 * @Since：2022/11/20
 * @Version：1.0.0
 */
@Route(path = RoutePath.Order.REFUND_DETAIL)
class RefundDetailActivity : BaseActivity<RefundDetailViewModel, ActivityRefundDetailBinding>(), OrderActionFinishListener {
    private val afterSaleNo by lazy { intent.getStringExtra(Constants.Order.REFUND_ID).toString() }

    private var mTimer: CountDownTimer? = null

    companion object {
        fun start(context: Context, refundId: String?) {
            var intent = Intent(context, RefundDetailActivity::class.java)
            intent.putExtra(Constants.Order.REFUND_ID, refundId)
            context.startActivity(intent)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTransparentForImageView(this, mDataBinding.titleBar)
    }

    override fun initData() {
        super.initData()
        mViewModel.getLogisticsCompany()
        mViewModel.getLogisticsInfo(afterSaleNo)
    }

    override fun onResume() {
        super.onResume()
        mViewModel.getRefundDetail(afterSaleNo)
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.mRefundDetail.observe(this) {
            OrderActionManager.getInstance(
                "",
                it.after_sale.after_sale_no,
                null,
                it.after_sale.after_sale_status,
                orderSource = OrderSource.REFUND_DETAIL,
                amount = "",
                actionResultListener = this
            ).addActionBt(mDataBinding.llBottomAction)
            checkCountDownTime(it)
        }
        mViewModel.mExpressInfoBean.observe(this) {
            //设置默认选中第一个
            mViewModel.currentExpressInfoBean.value = mViewModel.mExpressInfoBean.value

        }
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v?.id) {

            R.id.tv_submit_express_info -> { //提交物流信息
                KeyboardUtils.hideSoftInput(this)
                mViewModel.delivery(afterSaleNo) {
                    mViewModel.getRefundDetail(afterSaleNo)
                    mViewModel.getLogisticsInfo(afterSaleNo)
                }
            }
            R.id.ll_express_company -> { //选择快递公司
                mViewModel.getLogisticsCompany {
                    CommonChooseDialog(
                        this,
                        com.baozhun.mall.res.R.string.please_choose_express_company,
                        mViewModel.expressCompany.value,
                        it.map { it.name }.toMutableList() as MutableList<String>
                    ) { _: String, selectPosition: Int ->
                        mViewModel.expressCompany.value = it[selectPosition].name
                        mViewModel.expressCompanyCode = it[selectPosition].code
                    }.show()
                }
            }
            R.id.tv_expire_num -> { //复制物流编号
                copyToClipboard(mViewModel.currentExpressInfoBean?.value?.express_no)
                showToast(com.baozhun.mall.res.R.string.alr_copy)
            }
            R.id.cl_logistics_info -> { //详细信息
                LogisticsDetailActivity.start(this, arrayListOf<ExpressInfoBean?>().apply {
                    add(mViewModel.mExpressInfoBean.value)
                }, true)
            }
            R.id.tv_call_phone -> { //打电话
                startActivity(IntentUtils.getDialIntent(mViewModel.currentExpressInfoBean?.value?.express_phone.toString()))
            }
            R.id.tv_copy -> { //复制
                copyToClipboard(afterSaleNo)
                showToast(com.baozhun.mall.res.R.string.alr_copy)
            }

        }
    }

    /**
     * 检测是否需要倒计时
     */
    private fun checkCountDownTime(refundDetailBean: RefundDetailBean) {
        if (refundDetailBean.after_sale.after_sale_status == RefundStatus.WAIT_AUDIT.status ||
            refundDetailBean.after_sale.after_sale_status == RefundStatus.WAIT_RETURN_GOODS.status ||
            refundDetailBean.after_sale.after_sale_status == RefundStatus.WAIT_RECEIVE.status
        ) {
            var longTime =
                if (refundDetailBean.after_sale.after_sale_status == RefundStatus.WAIT_RETURN_GOODS.status) refundDetailBean.after_sale.delivery_expire_time else refundDetailBean.after_sale.audit_expire_time
            startCountDownTimer(longTime)
        }
    }

    /**
     * 开始倒计时
     */
    private fun startCountDownTimer(totalTime: Long) {
        if (totalTime <= 0) return
        mViewModel.mSurplusTime.value = totalTime * 1000
        mTimer?.cancel()
        mTimer = object : CountDownTimer(totalTime * 1000, 1000L) {
            override fun onTick(millisUntilFinished: Long) {
                mViewModel.mSurplusTime.value?.let {
                    mViewModel.mSurplusTime.value = it - 1000
                }
            }

            override fun onFinish() {
                mViewModel.getRefundDetail(afterSaleNo)
            }

        }
        mTimer?.start()
    }


    override fun onDestroy() {
        super.onDestroy()
        mTimer?.cancel()
    }

    override fun reload(orderActionType: OrderActionType?) {
        finish()
    }

}
